package org.jeecgframework.web.controller;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.poi.ss.formula.functions.Mode;
import org.hibernate.criterion.Restrictions;
import org.jeecgframework.core.common.controller.BaseController;
import org.jeecgframework.core.common.exception.BusinessException;
import org.jeecgframework.core.common.hibernate.qbc.CriteriaQuery;
import org.jeecgframework.core.common.model.json.AjaxJson;
import org.jeecgframework.core.common.model.json.DataGrid;
import org.jeecgframework.core.common.model.json.ValidForm;
import org.jeecgframework.core.constant.Globals;
import org.jeecgframework.core.util.*;
import org.jeecgframework.tag.core.easyui.TagUtil;
import org.jeecgframework.web.service.CbsServiceServiceI;
import org.jeecgframework.web.service.WxCommonService;
import org.jeecgframework.web.service.ZyCommonService;
import org.jeecgframework.web.service.ZyEquipmentSpareServiceI;
import org.jeecgframework.web.system.pojo.base.*;
import org.jeecgframework.web.system.pojo.vo.EquipInfo;
import org.jeecgframework.web.system.service.SystemService;
import org.jeecgframework.web.util.StaticValue;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;



/**   
 * @Title: Controller
 * @Description: 微信巡检功能
 * @author onlineGenerator
 * @date 2016-03-22 15:13:54
 * @version V1.0   
 *
 */
@Scope("prototype")
@Controller
@RequestMapping("/CbsWxInspectionController")
public class CbsWxInspectionController extends BaseController {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(ZyEquipmentSpareController.class); // NOPMD by dzqThinkpad on 16-4-1 下午3:02

	@Autowired
	private ZyEquipmentSpareServiceI zyEquipmentSpareService;
	@Autowired
	private SystemService systemService;
	@Autowired
	private ZyCommonService zyCommonService;
	@Autowired
	private WxCommonService wxCommonService;
	@Autowired
	private CbsServiceServiceI cbsServiceService;
	
	private String message;
	
	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}



	/*
	* 巡检查询
	* 马宏刚
	* */
	@RequestMapping(params = "goWxInspectionList")
	public ModelAndView goWxInspectionList(String sn){
		ModelAndView mv = new ModelAndView("com/wx/self_service/wx_inspection_list");
		List<ZyEquipmentSpareEntity> esList = systemService.findHql("from ZyEquipmentSpareEntity where isSpare = false and sn = ?",sn);
		mv.addObject("equip", esList);
		mv.addObject("sn", sn);
		String logo = "bg-logo-new.jpg";
		if(esList.size() > 0){
			if(esList.get(0).getType() != null && esList.get(0).getType().getEquipmentType() != null){
				String tempLogo = esList.get(0).getType().getEquipmentType().getLogo();
				if(StringUtil.isNotEmpty(tempLogo)){
					logo = tempLogo;
				}
			}
			String sql="select *from Zy_inspection_plan where equipment_spare_id='"+esList.get(0).getId()+"'and state!='k_inspection_cancel' and YEAR(ip_plan_date)=YEAR(NOW())";
			List<Map<String,Object>> iPlanList=systemService.findForJdbc(sql);
			mv.addObject("iplanList",iPlanList);
		}
		mv.addObject("logo",logo);
		Map<String, Object> map = new HashMap<String, Object>();
		for (int i = 0; i < esList.size(); i++) {
			Calendar cal=Calendar.getInstance();
			cal.setTime(esList.get(i).getRepairEndDate());
			Calendar date=Calendar.getInstance();
			date.setTime(new Date());
			map.put(esList.get(i).getId(), DateUtils.dateDiff('d',cal , date));

		}

		mv.addObject("map", map);
		//查询所有巡检计划状态
		List<TSType> planStateList=systemService.findHql("from TSType where TSTypegroup.typegroupcode='planState'");
		mv.addObject("planStateList", planStateList);
		return mv;
	}

	/*
	* 巡检变更申请页面
	* */
	@RequestMapping(params = "goWxInspectionUpdate")
	public ModelAndView goWxInspectionUpdate(ModelMap map,HttpServletRequest request) throws  Exception{
		ModelAndView mv = new ModelAndView("com/wx/self_service/wx_inspection_update");
//		TSUser user=ResourceUtil.getSessionUserName();
//		Date date=new Date();
//		String hql="from ZyContactsEntity where cellphone1='"+user.getMobilePhone()+"' or cellphone2='"+user.getMobilePhone()+"'";
//		List<ZyContactsEntity> zyContacts=systemService.findHql(hql);
//		if(zyContacts.size()>0){
//			mv.addObject("contacts",zyContacts.get(0));
//		}
//		CbsWxUserBindEntity wxUser=systemService.singleResult("from CbsWxUserBindEntity where openId='"+user.getOpenId()+"'");
//		mv.addObject("wxUser",wxUser);
//		mv.addObject("user",user);
//		mv.addObject("date",date);
		TSUser u = ResourceUtil.getSessionUserName();
		if(null != u){
			TSBaseUser bu = wxCommonService.get(TSBaseUser.class, u.getId());
			if(bu != null){
				List<ZyContactsEntity> cts = wxCommonService.findByProperty(ZyContactsEntity.class, "tsBaseUser.id", bu.getId());
				if(cts != null && cts.size() > 0 && cts.get(0)!= null){
					map.put("cinemaName",cts.get(0).getCinemaName());
				}
				if(bu.getAuthenticationLevel() !=null && bu.getAuthenticationLevel().equals("2")){//钻石（原金牌）用户
					List<CbsWxUserBindEntity> wubs = wxCommonService.findByProperty(CbsWxUserBindEntity.class, "openId", bu.getOpenId());
					if(wubs != null && wubs.size() > 0){
						map.put("cinemaChain",wubs.get(0).getChainName());
					}
				}
			}
		}
		map.put("page",u);
		Date dateNow=new Date();
		map.put("serviceDate",dateNow);
		map.put("sn",request.getParameter("sn"));
		return mv;
	}

	@RequestMapping(params = "subWxInspectionUpdate")
	@ResponseBody
	public AjaxJson subWxInspectionUpdate(HttpServletRequest request) {
		AjaxJson j = new AjaxJson();
		String openId = oConvertUtils.getString(request.getSession().getAttribute("openId"));
		String name = oConvertUtils.getString(request.getSession().getAttribute("name"));
		System.out.println("openId--"+openId);
		TSUser user=systemService.singleResult("from TSUser where openId='"+openId+"'");
		String createBy="";
		String createName="";
		if(user!=null && StringUtil.isNotEmpty(user.getUserName())){
			createBy=user.getUserName();
		}else{
			createBy=openId;
		}
		if(user!=null && StringUtil.isNotEmpty(user.getRealName())){
			createName=user.getRealName();
		}else{
			createName=name;
		}
		System.out.println("openId--"+openId);
		CbsServiceEntity service=new CbsServiceEntity();
		message = "巡检变更申请成功";

		String eqNumber=request.getParameter("equipmentNum");
		String serviceDate=request.getParameter("serviceDate");
		String sn=request.getParameter("sn");
		CbsServiceTypeEntity sType1=systemService.singleResult("from CbsServiceTypeEntity where type=0 and name='增值服务'");
		CbsServiceTypeEntity sType2=systemService.singleResult("from CbsServiceTypeEntity where type=1 and name='巡检变更'");
		try{
			service.setZyCinemaName(request.getParameter("cinemaName"));
			service.setTypename(request.getParameter("cinemaChain"));
			service.setContactsName(request.getParameter("contactsName"));
			service.setContactsPhone(request.getParameter("contactsPhone"));
			if(eqNumber!=null && !eqNumber.equals("")){
				service.setEquipmentNum(Integer.valueOf(eqNumber));
			}
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
			if(serviceDate!=null && !serviceDate.equals("")){
				service.setServiceDate(sdf.parse(serviceDate));
			}
			service.setDescription("设备台数:"+eqNumber+";希望服务时间:"+serviceDate);
			service.setServiceType1(sType1);
			service.setServiceType2(sType2);
			service.setSourceType("2");
			service.setStatus("1");
			service.setSn(request.getParameter("sn"));
			service.setSpeedStatus("0");
			ZyEquipmentSpareEntity zyEquipmentSpare=systemService.singleResult("from ZyEquipmentSpareEntity where sn='"+sn+"'");
			if(zyEquipmentSpare!=null){
				service.setZyEquipmentSpareId(zyEquipmentSpare);
				service.setTypeDec(zyEquipmentSpare.getType().getTypeDesc());
			}
			ZyCinemaEntity cinema=systemService.singleResult("from ZyCinemaEntity where name='"+request.getParameter("cinemaName")+"'");
			if(cinema!=null){
				service.setZyCinemaId(cinema);
				service.setProvince(cinema.getProvince());
				if(cinema.getCity()!=null){
					TSTerritory city=systemService.get(TSTerritory.class,cinema.getCity());
					service.setCity(city);
				}
				service.setAddress(cinema.getAddress());
			}

			String hql="from ZyContactsEntity where cellphone1='"+request.getParameter("contactsPhone")+"' or cellphone2='"+request.getParameter("contactsPhone")+"'";
			List<ZyContactsEntity> zyContacts=systemService.findHql(hql);
			if(zyContacts.size()>0){
				service.setZyContactsId(zyContacts.get(0));
			}

			//组装服务单号CR+YYYYMMDD+001(增长)
//			String code ="";
//			Date date = new Date();
//			DateFormat format = new SimpleDateFormat("YYYYMMdd");
//			String time = format.format(date);
//			StringBuffer buffer = new StringBuffer();
//			buffer.append("CR");
//			buffer.append(time);
//			List<Object[]> cbsServiceList = systemService.findListbySql("select * from cbs_service where `code` not LIKE '%-%' AND to_days(create_date) = to_days(now()) ORDER BY `code` desc");
//
//			if (cbsServiceList.size() == 0) {
//				buffer.append("001");
//				code= buffer.toString();
//			} else {
//				String o = (String) cbsServiceList.get(0)[1];
//				String s = o.substring(10, 13);
//				int i = Integer.parseInt(s);
//				i++;
//				if (i <= 9) {
//					buffer.append("00" + i);
//				} else if (i >= 10 && i < 100) {
//					buffer.append("0" + i);
//				} else {
//					buffer.append("" + i);
//				}
//				code = buffer.toString();
//			}
			Map m = cbsServiceService.getNo();

			service.setCode(m.get("no").toString());
			service.setCreateBy(createBy);
			service.setCreateName(createName);
			service.setCreateDate(new Date());
			systemService.save(service);
			//添加日志
			wxCommonService.addServiceLog(service.getId());

			//调用微信接口发送模板消息
			List<Map<String,String>> list=new ArrayList<>();
			String serviceCode="";
			if(service!=null){
				serviceCode=service.getCode();
			}
			String content="尊敬的客户：您的放映机<"+sn+">的服务申请已提交，服务单号：<"+serviceCode+">。我们会在30分钟内与您联系。【中影巴可客服部】";
			if(StringUtil.isNotEmpty(openId)){
				Map<String,String> map=new HashMap<>();
				map.put("openid",openId);
				map.put("message",content);
				list.add(map);
				wxCommonService.sendMsgForWx(list);
			}

			//发送邮件给HD
			wxCommonService.sendMail(service);


			systemService.addLog(message, Globals.Log_Type_INSERT, Globals.Log_Leavel_INFO);
		}catch(Exception e){
			e.printStackTrace();
			message = "巡检变更申请失败";
			throw new BusinessException(e.getMessage());
		}
		j.setObj(service.getCode());
		j.setMsg(message);
		return j;
	}
}
